// 用户注册API
import { NextRequest, NextResponse } from 'next/server';
import { UserDB } from '@/lib/mysql';
import {
  hashPassword,
  generateToken,
  validateUsername,
  validatePassword,
  validateEmail,
  ApiResponse,
} from '@/lib/auth';

const JWT_EXPIRES_IN = parseInt(process.env.JWT_EXPIRES_IN || '86400');

export async function POST(request: NextRequest) {
  try {
    // 解析请求体
    const body = await request.json();
    const { username, password, email, school, gradeLevel } = body;

    // 验证必填字段
    if (!username || !password) {
      return ApiResponse.error('用户名和密码不能为空');
    }

    // 验证用户名格式
    const usernameValidation = validateUsername(username);
    if (!usernameValidation.valid) {
      return ApiResponse.error(usernameValidation.error!);
    }

    // 验证密码格式
    const passwordValidation = validatePassword(password);
    if (!passwordValidation.valid) {
      return ApiResponse.error(passwordValidation.error!);
    }

    // 验证邮箱格式（如果提供）
    if (email) {
      const emailValidation = validateEmail(email);
      if (!emailValidation.valid) {
        return ApiResponse.error(emailValidation.error!);
      }
    }

    // 检查用户名是否已存在
    const usernameExists = await UserDB.usernameExists(username);
    if (usernameExists) {
      return ApiResponse.error('用户名已被使用');
    }

    // 检查邮箱是否已存在（如果提供）
    if (email) {
      const emailExists = await UserDB.emailExists(email);
      if (emailExists) {
        return ApiResponse.error('邮箱已被使用');
      }
    }

    // 加密密码
    const passwordHash = await hashPassword(password);

    // 创建用户
    const userId = await UserDB.create(username, passwordHash, email);

    // 获取完整用户信息
    const user = await UserDB.findById(userId);
    if (!user) {
      return ApiResponse.serverError('用户创建失败');
    }

    // 更新用户配置（如果提供了学校和年级）
    if (school || gradeLevel) {
      const { query } = await import('@/lib/mysql');
      await query(
        `UPDATE user_profiles SET school = ?, grade = ? WHERE user_id = ?`,
        [school || null, gradeLevel || 1, userId]
      );
    }

    // 生成Token
    const token = generateToken(user);

    // 创建响应
    const response = NextResponse.json(
      {
        success: true,
        message: '注册成功',
        data: {
          user: {
            id: user.id,
            username: user.username,
            email: user.email,
            displayName: user.display_name,
            role: user.role,
          },
          token,
        },
      },
      { status: 200 }
    );

    // 设置Cookie
    response.cookies.set('token', token, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: JWT_EXPIRES_IN,
      path: '/',
    });

    return response;
  } catch (error) {
    console.error('注册错误:', error);
    return ApiResponse.serverError('注册失败，请稍后重试');
  }
}

// 不允许其他HTTP方法
export async function GET() {
  return ApiResponse.error('方法不允许', 405);
}

export async function PUT() {
  return ApiResponse.error('方法不允许', 405);
}

export async function DELETE() {
  return ApiResponse.error('方法不允许', 405);
}
